<template>
  <el-container
    style="height: calc(100vh - 90px); border: 1px solid #eee"
    class="bg_index"
  >
    <el-aside width="400px">
      <el-card
        v-model="stuForm"
        :cell-style="cellStyle"
        :header-cell-style="rowClass"
        style="margin-left: 50px"
      >
        <el-descriptions :column="1" border>
          <el-descriptions-item label="姓名"
            ><template slot="label">
              <i class="el-icon-user"></i>
              用户名
            </template>
            {{userInfo.name}}</el-descriptions-item
          >
          <el-descriptions-item label="学号"
            ><template slot="label">
              <i class="el-icon-view"></i>
              学号
            </template>
            {{userInfo.id}}
          </el-descriptions-item>
        </el-descriptions>
        <div>
          <h3>答题卡</h3>
          <!-- <div v-for="(question, index) in questionAnswerDataList" :key="index">
            <div v-if="question.questionType==1">
                <h3>选择题</h3>
                    <el-button
              :key="++index"
              size="medium"
              @click="selectQuestion(index)"
              circle
              :class="
                question.studentAnswer != null && question.studentAnswer != ''
                  ? 'isAnswerClass'
                  : ''
              "
              >{{ index }}</el-button
            >
            </div>
        
          </div> -->
          <!-- <h3>选择题</h3> -->
          <!-- <template v-for="(question, index) in questionAnswerDataListObjList">
            <el-button
              :key="++index"
              size="medium"
              @click="selectQuestion(index)"
              circle
              :class="
                question.studentAnswer != null && question.studentAnswer != ''
                  ? 'isAnswerClass'
                  : ''
              "
              >{{ index }}</el-button
            >
          </template> -->
          <div
            v-for="(item, index1) in questionAnswerDataListObjList"
            :key="index1"
          >
            <p class="card-title">{{ item.questionTypeName }}</p>
            <!-- <h6>{{ item.questionTypeName }}</h6> -->
            <div style="display: flex">
              <br />
              <div
                v-for="(question, index) in item.answers"
                :key="index"
                style="flex-direction: row"
              >
                <el-tag
                  :key="++index"
                  size="medium"
                  :class="question.studentAnswer==''&&question.studentAnswer==null?'istag':''"
                  @click="selectQuestion(question.sort)"
                  :type="cardItemClass(question.studentAnswer, question.sort)"
                  >{{ question.sort }}</el-tag
                >
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </el-aside>

    <el-main>
      <div class="container learnstyle-page">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span
              >{{ testPaperInfo ? testPaperInfo.name : "" }} (共{{
                testPaperInfo ? testPaperInfo.questionNumber : ""
              }}题 合计{{ testPaperInfo ? testPaperInfo.mark : "" }}分)</span
            >
            <span style="float: right">剩余时间: {{ timeValue }}分钟</span>
          </div>

          <question-info
            :showNumberTitle="false"
            @openWritingBoard="openWritingBoard"
            :timeOutFlag="timeOutFlag"
            commitButtonText="提交试卷"
            @afterCommit="afterCommit"
            :questionInfoAnswerList="testPaperInfoQuestionList"
            :testPaperID="testPaperID"
            @getQuestionAnswerDataList="getQuestionAnswerDataList"
            :index="currentQuestionPage"
            @getCurrentQuestionPage="getCurrentQuestionPage"
          >
          </question-info>
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { clearLoginInfo } from "@/api/common";
import { mapGetters } from "vuex";
import questionInfo from "@/components/question-info";
import questionlist from "@/components/question-list";
export default {
  name: "examDetils",
  components: { questionInfo, questionlist },
  data() {
    return {
      //考生信息
      stuForm: {
        name: null,
        number: null,
      },
      form: "",
      list: [],
      studentExamTime: 0, // 学生考试用时
      studentExamTimer: null,
      examTime: null,
      //   timeInterval: null,
      timeTarget: null,
      endTime: null,
      timeOutFlag: false, // 是否考试时间到
      openAnswerFlag: false,
      leaveNumber: 0,

      testPaperInfoQuestionList: [], // 存储用户答题答案及试题答案解析
      currentPage: 0,
      timeValue: 0,
      pageSize: 1,
      totalCount: 0,
      openWritingBoardFlag: false,
      questionTypeList: [],
      testPaperOBJ: [],
      testPaperID: null,

      questionAnswerDataList: [],
      currentQuestionPage: 1,
      currentQuestion: {
        questionTypeName: '',
        answers: []
      },

      questionAnswerDataListObjList: [

      ],
      indexAnswer: 0,
    };
  },
  computed: {
    ...mapGetters({
      testPaperInfo: "common/getTestPaperInfo",
    }),
    ...mapGetters({
      userInfo: "user/getUserInfo",
    }),
  },
  beforeCreate() { },
  created() {
    this.getTestPaperList()
    this.getExamCountdown()//倒计时
  },
  mounted() {
    if (this.testPaperInfo !== null) {
      let examTimeObj = sessionStorage.getItem("examTime");
      if (examTimeObj) {
        this.examTime = parseInt(examTimeObj); //parseInt(examTimeObj) * 60 * 1000
      } else {
        this.examTime = this.testPaperInfo.examTime * 60 * 1000;
      }
      let now = new Date().getTime();
      this.endTime = now + this.examTime;
      this.timeTarget = setInterval(() => {
        this.startTime(); // 开始倒计时
      }, 100);

    }

    this.studentExamTimer = setInterval(() => {
      this.startCountStudentExamTime(); // 开始计算考试时间
      // this.getExamCountdown();
    }, 1000);
    this.getPaperQuestionList();
    document.addEventListener("visibilitychange", this.visibilityChangeEvent);


    var time = setInterval(() => {
      this.getExamCountdown()// 获取倒计时
    }, 60000);
  },

  destroyed() {
    document.removeEventListener(
      "visibilitychange",
      this.visibilityChangeEvent
    );
    clearInterval(this.timeTarget);
    clearInterval(this.studentExamTimer);
  },
  methods: {
    getCurrentQuestionPage(val){
      this.currentQuestionPage =val+1
    },

    cardItemClass(answered, sort) {
      console.log(answered,sort)
      if (sort === this.currentQuestionPage) {
        return 'warning'
      }

      if (answered!=null&&answered!='') {
        return 'success'
      }

      if (!answered||answered.length==0) {
        return 'info'
      }
    },
    // 答题卡切换试题
    selectQuestion(index) {
      this.currentQuestionPage = index;

      // this.currentQuestion = this.questionAnswerDataList[this.currentQuestionPage];
      //     this.studentQuestionList.forEach(element => {
      //     if (element.questionInfoId == this.currentQuestion.questionInfoId) {
      //       this.currentQuestion.studentAnswer = element.studentAnswer;
      //       this.content = this.currentQuestion.studentAnswer;
      //     }
      //   });

      // this.parserQuestion();
      // this.openAnswerFlag = false;
    },
    getQuestionAnswerDataList(val) {
      this.questionAnswerDataList = val
      let questionIndex = 0
      let arr = {
        questionTypeName: '',
        answers: []
      }
  
      this.questionAnswerDataList.forEach((item) => {

        if (item.questionType == 1) {
          questionIndex++
          item.sort = questionIndex
          arr.questionTypeName = item.questionTypeName
          arr.answers.push(item)

        }

      })
      this.questionAnswerDataListObjList.push(arr)
      arr = {
        questionTypeName: '',
        answers: []
      }

      this.questionAnswerDataList.forEach((item) => {

        if (item.questionType == 2) {
          questionIndex++
          item.sort = questionIndex
          arr.questionTypeName = item.questionTypeName
          arr.answers.push(item)
        }

      })

      this.questionAnswerDataListObjList.push(arr)
      arr = {
        questionTypeName: '',
        answers: []
      }
      this.questionAnswerDataList.forEach((item) => {

        if (item.questionType == 6) {
          questionIndex++
          item.sort = questionIndex
          arr.questionTypeName = item.questionTypeName
          arr.answers.push(item)
        }

      })

      this.questionAnswerDataListObjList.push(arr)
      arr = {
        questionTypeName: '',
        answers: []
      }
      this.questionAnswerDataList.forEach((item) => {

        if (item.questionType == 3) {
          questionIndex++
          item.sort = questionIndex
          arr.questionTypeName = item.questionTypeName
          arr.answers.push(item)
        }

      })
      this.questionAnswerDataListObjList.push(arr)
      arr = {
        questionTypeName: '',
        answers: []
      }
      this.questionAnswerDataList.forEach((item) => {

        if (item.questionType == 7) {
          questionIndex++
          item.sort = questionIndex
          arr.questionTypeName = item.questionTypeName
          arr.answers.push(item)
        }

      })
      this.questionAnswerDataListObjList.push(arr)
      arr = {
        questionTypeName: '',
        answers: []
      }
      this.questionAnswerDataList.forEach((item) => {

        if (item.questionType == 4) {
          questionIndex++
          item.sort = questionIndex
          arr.questionTypeName = item.questionTypeName
          arr.answers.push(item)
        }

      })
      this.questionAnswerDataListObjList.push(arr)
      //      this.currentQuestion.questionTypeName = '判断题'
      //     this.questionAnswerDataList.forEach((item) => {
      //       if (item.questionType == 6) {
      //         // this.currentQuestion.questionTypeName = item.questionTypeName
      //         this.currentQuestion.answers.push(item)
      //       }

      //     })
      //     this.questionAnswerDataListObjList.push(this.currentQuestion)
      //      this.currentQuestion.questionTypeName = '填空题'
      //     this.questionAnswerDataList.forEach((item) => {
      //       if (item.questionType == 3) {
      //         // this.currentQuestion.questionTypeName = item.questionTypeName
      //         this.currentQuestion.answers.push(item)
      //       }

      //     })
      //     this.questionAnswerDataListObjList.push(this.currentQuestion)
      console.log('questionAnswerDataListObjList', this.questionAnswerDataListObjList)
    },
    //获取考生信息  id
    //  getstudent () {
    //   const that = this
    //   this.axios.get(this.$httpApi.httpUrl (this.userInfo.id))
    //     .then(function (response) {
    //       that.stuForm = response.data.content
    //     })
    //  },

    getTestPaperList() {
      this.axios
        .get(this.$httpApi.httpUrl("/student/testPaperInfo/list"), {})
        .then((response) => {
          this.testPaperOBJ = response.data.data.dataList;
          this.testPaperID = this.testPaperOBJ[0].id
          // console.log("试卷ID:", this.testPaperID);
        });
    },
    // 考试倒计时
    getExamCountdown() {
      let ids = ''
      ids = this.userInfo.id
      this.axios
        .get(this.$httpApi.httpUrl("/getExamCountdown"), {
          params: {
            taskId: this.testPaperInfo.examTaskId
          }
        })
        .then((response) => {
          this.timeValue = response.data.data
          if (this.timeValue == 0) {
            this.axios
              .get(this.$httpApi.httpUrl(`/testStudent/closeState`), {
                params: {
                  ids
                }
              })
              .then((response) => {
                this.logout()
              });
          }


          // console.log("试卷ID:", this.testPaperID);
        });
    },

    // 退出验证提示
    logout() {
      let that = this;

      that.logoutCommon(that);

    },
    //退出登录
    logoutCommon(that) {
      that.axios
        .post(that.$httpApi.httpUrl("/student/logout"))
        .then(function (response) {
          if (response.data.code === 1) {
            that.$message({
              type: "success",
              message: response.data.message,
            });
            clearLoginInfo();
            setTimeout(function () {
              that.$router.push({ name: "login" });
            }, 1000);
          } else {
            that.$message({
              type: "error",
              message: response.data.message,
            });
          }
        });
    },
    openWritingBoard() {
      this.openWritingBoardFlag = true;
    },

    startCountStudentExamTime() {
      this.studentExamTime++;
    },

    // 监听页面离开事件
    visibilityChangeEvent(e) {
      // alert(document.location.href)
      /* if (document.hidden) {
            if (!this.openWritingBoardFlag) {
              this.leaveNumber++
            }
            // alert('hidden')
          } else {
            this.openWritingBoardFlag = false
            //// alert('show')
          }*/
      // alert(this.leaveNumber)
      /* this.leaveNumber++
          if (this.leaveNumber === 6) {
            console.log('作弊, 系统自动提交')
          }
          if (this.leaveNumber % 2 !== 0) {
            this.$alert('考试中请勿离开当前页面，超过3次系统将自动提交', '考试注意事项', {
              confirmButtonText: '确定',
              callback: action => {

              }
            })
          }*/
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      return "text-align:center";
    },

    rowClass({ row, rowIndex }) {
      return "text-align:center";
    },

    startTime() {    // if (this.timeValue === "0:00:00" || this.timeValue === "00:00:00") {
      //   clearInterval(this.timeTarget);
      //   this.$notify({
      //     title: "警告",
      //     duration: 2000,
      //     message: "考试时间到,系统将自动提交本次考试",
      //     type: "warning",
      //   });
      //   setTimeout(() => {
      //     this.timeOutFlag = true;
      //   }, 100);
      //   return false;
      // }
      // let nowTime = new Date().getTime();
      // let chaTime = this.endTime - nowTime;
      // //倒计时的时间
      // if (chaTime >= 0) {
      //   let d = Math.floor(chaTime / 1000 / 60 / 60 / 24);
      //   let h = Math.floor((chaTime / 1000 / 60 / 60) % 24);
      //   if (h <= 9) {
      //     h = 0 + "" + h;
      //   }
      //   let m = Math.floor((chaTime / 1000 / 60) % 60);
      //   if (m <= 9) {
      //     m = 0 + "" + m;
      //   }
      //   let s = Math.floor((chaTime / 1000) % 60);
      //   if (s <= 9) {
      //     s = 0 + "" + s;
      //   }
      //   if (d > 0) {
      //     this.timeValue = d + "天" + h + "时" + m + "分" + s + "秒";
      //   } else {
      //     this.timeValue = h + ":" + m + ":" + s;
      //   }
      // }
      // this.examTime = this.examTime - 1000;
      // // 缓存考试时间，防止刷新页面考试时间仍然不变的问题
      // sessionStorage.setItem("examTime", this.examTime);

    },

    // selectQuestion(index) {},

    // 答题卡
    openAnswerSheet() {
      this.openAnswerFlag = true;
    },

    // 获取试卷试题列表
    getPaperQuestionList() {
      //  console.log(   "id:",this.testPaperInfo)
      let arr = []
      this.axios
        .get(
          this.$httpApi.httpUrl(
            "/student/testPaperInfo/selectPaperQuestionById"
          ),
          {
            params: {
              id: this.testPaperInfo.id
              //  id:1
            },
          }
        )
        .then((response) => {
          // console.log('鹿皮皮', response)
          arr = response.data.data.dataList;
          // this.testPaperInfoQuestionList.sort((a,b)=>{
          //       return a.questionType - b.questionType;
          //   })
          arr.forEach((item) => {
            if (item.questionType == 1) {
              this.testPaperInfoQuestionList.push(item)
            }
          })
          arr.forEach((item) => {
            if (item.questionType == 2) {
              this.testPaperInfoQuestionList.push(item)
            }
          })

          arr.forEach((item) => {
            if (item.questionType == 6) {
              this.testPaperInfoQuestionList.push(item)
            }
          })
          arr.forEach((item) => {
            if (item.questionType == 3) {
              this.testPaperInfoQuestionList.push(item)
            }
          })
          arr.forEach((item) => {
            if (item.questionType !== 1 &&
              item.questionType !== 2 &&
              item.questionType !== 6 && item.questionType !== 3) {
              this.testPaperInfoQuestionList.push(item)
            }
          })
          this.testPaperInfoQuestionList.forEach((item) => {
            let questionType = item.questionType;
            if (questionType !== 1 && questionType !== 6) {
              this.$set(item, "studentAnswer", []);
              //  item.studentAnswer = [] 此方式会导致v-model 无法绑定变量
            } else {
              this.$set(item, "studentAnswer", "");
            }
          });

        });

      // this.testPaperInfoQuestionList.forEach(()=>{

      // })
    },

    afterCommit(questionAnswerParam) {
      clearInterval(this.studentExamTimer);
      let params = {
        examTime: this.studentExamTime,
        testPaperInfoId: this.testPaperInfo.id,
        questionAnswerList: questionAnswerParam,
      };
      this.axios
        .post(
          this.$httpApi.httpUrl("/student/testPaperInfo/commitPaper"),
          params
        )
        .then((response) => {
          this.$message.success("提交成功");
          this.$router.push("examHistory");
        });
    },
  },
  filters: {},
};
</script>

<style scoped lang="scss">
.istag{
  background-color:#eee;
   color: #616466
 }
.card-title {
  background: #eee;
  line-height: 35px;
  text-align: center;
  font-size: 14px;
}
// .container {
//   height: calc(100vh - 90px);
//   background-color: #f9f9f9;
// }

/deep/ .el-card__body {
  padding: 0 0 0 !important;
}
// .box-card {
//   margin-top: 5px;
//   // background: rgba(1, 0, 0, 0.1);
// }
// p {
//   word-break: keep-all;
//   white-space: nowrap;
//   overflow: hidden;
//   text-overflow: ellipsis;
// }
/deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
  background-color: #409eff !important;
  border-color: #409eff !important;
}

/deep/ .el-checkbox__input.is-disabled.is-checked + span.el-checkbox__label {
  color: #409eff !important;
}
.bg_index {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  // background: url("/static/image/1.jpg");
  background-size: 100% 100%;
  background-position: center;
  position: fixed;
}
.exam_time {
  color: red;
  font-size: 24px;
  position: relative;
  left: 30%;
  bottom: 80%;
}

.back {
  color: #ca0000;
  cursor: pointer;
}

.text {
  font-size: 14px;
}
.oper-btn {
  position: relative;
  left: 35%;
  margin-top: 50px;
}
.radio-item {
  line-height: 40px;
  margin-left: 20px;
}
.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card p {
  display: inline;
}

.box-card {
  width: 100%;
}
.box-card >>> p {
  display: inline-block;
}
</style>